package org.qingke.mail.authenication;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.qingke.mail.common.CookieHelper;
import org.qingke.mail.common.Response;
import org.qingke.mail.common.SSORequest;
import org.qingke.mail.util.LoggerUtil;
import org.qingke.mail.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Token认证(登录认证拦截器)
 * 该拦截器应用在所有需要sso认证的应用中
 *
 */
@Component
public class TokenAuthenicationInterceptor implements HandlerInterceptor{
    
	// SSO登录地址
	@Value("${sso.login.url}")
	private String ssoLoginUrl;
	// SSO认证地址
	@Value("${sso.authenication.url}")
	private String ssoAuthenicationUrl;
	
	@Autowired
	private RestTemplate restTemplate;
	

	private LoggerUtil logger = LoggerUtil.getLogger(getClass());
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//获取token请求地址
		String token=CookieHelper.getCookie("token",request);
		String requestUrl=request.getRequestURI().toString();
		logger.info("interceptor token: " + token + " url: " + requestUrl);
		
		// 如果token部位空则根据token查询 用户信息,调用sso系统的接口。
		if(StringUtil.hasEmpty(token)){
			//构建SSO请求对象
			SSORequest ssoRequest=SSORequest.getSSORequest();
			ssoRequest.setToken(token);
			ssoRequest.setRedirectUrl(request.getRequestURI().toString());
			//认证
			Response ssoResponse=restTemplate.postForEntity(ssoAuthenicationUrl, ssoRequest, Response.class).getBody();
			logger.info("authenication sso response: " + ssoResponse);
			//认证成功
			if(ssoResponse.isState()){
				return true;
			}
		}
		
		//如果token为空,跳转到sso登录页面，将请求url作为参数传递给sso
		response.sendRedirect(ssoLoginUrl+"?redirect"+request.getRequestURI());
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	

}
